<?php
// +----------------------------------------------------------------------
// | 常用函数库
// +----------------------------------------------------------------------
/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8",$suff=true) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    if(mb_strlen($str, 'utf8') > $length && $suff){
        return $slice.'...';
    }else{
        return $slice;
    }
}

function clear_tag($str) {
    $str = preg_replace ( '/<t(.+?)>/', '', $str );
    $str = preg_replace ( '/<\/t(.+?)>/', '', $str );
    $str = preg_replace ( '/<iframe(.+?)><\/iframe>/', '', $str );
    $str = preg_replace ( '/<script(.+?)><\/script>/', '', $str );
    $str = preg_replace ( '/<div (.+?)>/', '', $str );
    $str = preg_replace ( '/<a(.+?)>/', '', $str );
    $str = preg_replace ( '/<(.+?)>/', '', $str );
    $str = preg_replace ( '/<img(.+?)>/', '', $str );
    $str = preg_replace ( '/&nbsp;/', '', $str );
    return $str;
}

/**
 * js返回跳转
 * @access public
 * @param string $url 地址
 * @return string
 */
function back($url="")
{
    if(!empty($url)){
        return "javascript:location.href='{$url}'";
    }else{
        return "javascript:history.go(-1);";
    }
}

/**
 * 格式化的打印
 * @param array $arr
 * @return array
 */
function print_g($arr=array(),$is_exit=true)
{
    dump($arr);
    if($is_exit){
        exit;
    }
}

//隐藏替换
function half_replace($str,$fNum=3,$bNum=4){
    $len = strlen($str)-($fNum+$bNum);
    return substr_replace($str,str_repeat('*',$len),$fNum,$len);
}

//隐藏中文姓名
function showName($name){
    if(empty($name)){
        return '';
    }
        if (mb_strlen($name) == 6) {
            $out = mb_substr($name, 0, 3) . '*';
        } else if (mb_strlen($name) == 9) {
            $out = mb_substr($name, 0, 6) . '*';
        } else if (mb_strlen($name) == 12) {
            $out = mb_substr($name, 0, 6) . '**';
        } else if (mb_strlen($name) == 3) {
            $out = substr($name, 0, 3) . '*';
        } else {
            $out = '*' . substr($name, -1, 1);
        }
    return $out;
}

/**
 * 判断图片是否存在
 * @param  [type] $url      [远程的图片路径]
 * @return [boolean]        [判断图片是否存在 true 不]
 */
function img_exits($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1); // 不下载
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $contents = curl_exec($ch);
    if (preg_match("/404/", $contents)){
        return false;
    } else {
        return true;
    }
}

/**
 * 获取客户端浏览器类型
 * @param  string $glue 浏览器类型和版本号之间的连接符
 * @return string|array 传递连接符则连接浏览器类型和版本号返回字符串否则直接返回数组 false为未知浏览器类型
 */
function get_client_browser($glue = '-v') {
    $browser = array();
    $agent = $_SERVER['HTTP_USER_AGENT']; //获取客户端信息

    /* 定义浏览器特性正则表达式 */
    $regex = C('Validator.browser');
    foreach($regex as $type => $reg) {
        preg_match($reg, $agent, $data);
        if(!empty($data) && is_array($data)){
            $browser = $type === 'safari' ? array($data[2], $data[1]) : array($data[1], $data[2]);
            break;
        }
    }
    return empty($browser) ? false : (is_null($glue) ? $browser : implode($glue, $browser));
}


//获取访问者的操作系统
function get_client_os(){
    $os = 'other';
    $userAgent = strtolower($_SERVER["HTTP_USER_AGENT"]);
    if($re  = strripos($userAgent,'iphone')){
        $os = 'iphone';
    }else if($re = strripos($userAgent,'android')){
        $os = 'android';
    }else if($re = strripos($userAgent,'micromessenger')){
        $os = 'weixin';
    }else if($re = strripos($userAgent,'ipad')){
        $os = 'ipad';
    }else if($re = strripos($userAgent,'ipod')){
        $os = 'ipod';
    }else if($re = strripos($userAgent,'windows nt')){
        $os = 'pc';
    }
    return $os;
}


/**
 * 验证器
 * @param $viledName 验证名称
 * @return array
 */
function validator($viledName,$m='regex',$title=''){
    $validData = C('Validator.rules');
    if(!empty($validData[$viledName])){
        $info = $validData[$viledName][$m];
        if(!empty($title) && $m=='error'){
            $info = $title.' : '.$info;
        }
        return $info;
    }else{
        return false;
    }
}


/**
 * 判断是否是微信内置浏览器打开
 * @return bool
 */
function is_Weixin()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
        return true;
    }
    return false;
}
/*
 * 对二维数组按照某个字段进行排序
 * */
function list_sort_by($list, $field, $sortby = 'asc')
{
    if (is_array($list))
    {
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
        {
            $refer[$i] = &$data[$field];
        }
        switch ($sortby)
        {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc': // 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val)
        {
            $resultSet[] = &$list[$key];
        }
        return $resultSet;
    }
    return false;
}

//设置金额格式
function set_money($m){
    return number_format($m,2,'.','');
}

/***
 * 通过数据库获取uuid
 * @return mixed
 */
function getUUID(){
    $sql ='select UUID() as uuid';
    $rst = M('')->query($sql);
    return $rst[0]['uuid'];
}
function getRandString($length,$type,$addChars=''){
    switch($type){
        case 'letter': //小写字母
            $tempType = 0;
            break;
        case 'num': //数字
            $tempType = 1;
            break;
        case 'upLetter': //大写字母
            $tempType = 2;
            break;
        case 'lowLetter'://小写字母
            $tempType = 3;
            break;
        case 'cn'://中文
            $tempType = 4;
            break;
        default: //所有
            $tempType = 5;

    }
   return  Org\Util\String::randString($length,$tempType,$addChars);
}
/**
 * 发送HTTP请求方法
 * @param  string $url    请求URL
 * @param  array  $params 请求参数
 * @param  string $method 请求方法GET/POST
 * @return array  $data   响应数据
 */
function http($url, $params, $method = 'GET', $header = array(), $multi = false){
    $opts = array(
        CURLOPT_TIMEOUT        => 30,//执行超时时间 秒
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER     => $header,
        CURLOPT_CONNECTTIMEOUT => 30,//链接超时时间 秒
        CURLOPT_SSL_VERIFYPEER => FALSE,
        CURLOPT_SSL_VERIFYHOST => FALSE,

    );
    /* 根据请求类型设置特定参数 */
    switch(strtoupper($method)){
        case 'GET':
            if(strpos($url,'?')){
                $opts[CURLOPT_URL] = $url . http_build_query($params);
            }else{
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            }
            break;
        case 'POST':
            //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception('不支持的请求方式！');
    } //dump ($opts);
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data  = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if($error) throw new Exception('请求发生错误：' . $error);
    return  $data;
}
function console_log($data){
    Common\Common\Console::log($data);
}